<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import {
    useConnectFieldForm,
    useGetCustomFieldOptions,
    useGetCustomFieldConnectDetail,
  } from '@/services/pages/return-factory/useModule'
  import { FormInstance } from 'element-plus'
  import _ from 'lodash'
  import { ref, watch } from 'vue'

  const { form, submitLoading, submit, resetForm } = useConnectFieldForm()
  const { loading, options, getOptionsParam, getOptions } = useGetCustomFieldOptions()
  const { detail, loading: getDetailLoading, getDetail } = useGetCustomFieldConnectDetail()

  defineOptions({
    name: 'CustomFieldConnectModalReturnFactoryModuleDetail',
  })

  const props = defineProps({
    connectFieldId: {
      type: String,
      default: () => '',
    },
    moduleId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel('visible', { type: Boolean, default: false })
  const formInstance = ref<FormInstance | null>(null)
  const rules = ref({
    repairFieldId: [{ required: true, message: '请选择字段', trigger: ['change', 'blur'] }],
  })

  const hideDialog = () => {
    visible.value = false
    resetForm()
  }

  const handleGetCustomFieldOptions = _.debounce((keyword: string) => {
    if (getOptionsParam.value.name !== keyword) {
      getOptionsParam.value.name = keyword
      getOptions()
    }
  }, 600)

  const onSubmit = async () => {
    if (formInstance.value) {
      try {
        form.value.repairModuleId = props.moduleId
        await formInstance.value.validate()
        const res = await submit()
        if (res.code === 20000) {
          emits('update')
          hideDialog()
          HMessage.success(infoTip.returnFactory.moduleConnectCustomField.connect_field_success)
          return
        }
        HMessageBox.error(
          infoTip.returnFactory.moduleConnectCustomField.err_code[res.code] || res.message,
        )
      } catch (error) {
        // error
      }
    }
  }

  watch(
    visible,
    async (value) => {
      if (value) {
        getOptions()

        if (props.connectFieldId) {
          await getDetail(props.connectFieldId)
          form.value = detail.value
        }
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-dialog
    v-model="visible"
    :title="!!props.connectFieldId ? '编辑关联字段' : '添加关联字段'"
    :loading="submitLoading || getDetailLoading"
    @close="hideDialog"
  >
    <el-form
      ref="formInstance"
      :model="form"
      inline-message
      label-position="top"
      class="modal_form_content"
      :rules="rules"
    >
      <el-form-item label="关联字段" prop="repairFieldId">
        <el-select
          v-model="form.repairFieldId"
          placeholder="请选择字段"
          :loading="loading"
          filterable
          :filter-method="handleGetCustomFieldOptions"
        >
          <el-option
            v-for="(customField, customFieldIndex) in options"
            :key="customFieldIndex"
            :label="customField.name"
            :value="customField.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="same_line">
        <el-form-item label="移动端是否显示" class="swtich-container-size-small">
          <el-switch v-model="form.mobileShow" size="small"></el-switch>
          <div class="text">{{ form.mobileShow ? '显示' : '隐藏' }}</div>
        </el-form-item>
        <el-form-item label="是否必填" class="swtich-container-size-small">
          <el-switch v-model="form.required" size="small"></el-switch>
          <div class="text">{{ form.required ? '必填' : '不必填' }}</div>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onSubmit">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>
